<template>
	<view class="cart-container">
		<!-- 地址选择 -->
		<view class="address-selector" @click="loadAddresses">
			<text class="section-title">收货地址</text>
			<view class="address-info" v-if="selectedAddress">
				<text class="address-name">{{ selectedAddress.name || '收货人' }}</text>
				<text class="address-phone">{{ selectedAddress.phone || '电话号码' }}</text>
				<text class="address-detail">{{ selectedAddress.province }}{{ selectedAddress.detailAddress }}</text>
			</view>
			<view class="address-info no-address" v-else>
				<text>请选择收货地址</text>
			</view>
		</view>
		
		<view class="cart-header">
			<label class="select-all">
				<checkbox :checked="isAllSelected" @click="toggleSelectAll"></checkbox>
				<text>全选</text>
			</label>
			<button @click="fetchCartItems">刷新购物车</button>
		</view>
		<view class="cart-item" v-for="item in cartItems" :key="item.cartId">
			<checkbox :checked="item.selected" @click="toggleSelectItem(item)"></checkbox>
			<view class="item-info">
				<text>{{ item.productName }}</text>
				<text>￥{{ item.price }}</text>
				<view class="quantity-selector">
					<button @click="decreaseQuantity(item)">-</button>
					<input type="number" v-model="item.buyNum" />
					<button @click="increaseQuantity(item)">+</button>
				</view>
			</view>
			<button @click="removeFromCart(item.cartId)">删除</button>
		</view>
		<view class="cart-footer">
			<text>已选 {{ selectedCount }} 件商品</text>
			<button @click="placeOrder">下单</button>
		</view>
		
		<!-- 地址选择弹窗 -->
		<view class="address-popup" v-if="showAddressPopup">
			<view class="popup-header">
				<text>选择收货地址</text>
				<text class="close-btn" @click="showAddressPopup = false">×</text>
			</view>
			<view class="address-list">
				<view 
					class="address-item" 
					:class="{ selected: selectedAddress && address.addressId === selectedAddress.addressId }"
					v-for="address in addresses" 
					:key="address.addressId"
					@click="selectAddress(address)"
				>
					<view class="address-main">
						<text class="address-name">{{ address.name || '收货人' }}</text>
						<text class="address-phone">{{ address.phone || '电话号码' }}</text>
						<text class="address-tag" v-if="address.isDefault">默认</text>
					</view>
					<text class="address-detail">{{ address.province }}{{ address.detailAddress }}</text>
				</view>
			</view>
			<button class="add-address-btn" @click="addAddress">新增地址</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		data() {
			return {
				cartItems: [],
				addresses: [],
				selectedAddress: null,
				showAddressPopup: false,
			};
		},
		computed: {
			selectedCount() {
				return this.cartItems.filter(item => item.selected).reduce((count, item) => count + item.buyNum, 0);
			},
			isAllSelected() {
				return this.cartItems.length > 0 && this.cartItems.every(item => item.selected);
			},
			customerId() {
				const userInfo = uni.getStorageSync('userInfo');
				return userInfo ? userInfo.customerId : null;
			}
		},
		methods: {
			...mapMutations(['setCartCount']),
			async fetchCartItems() {
				if (!this.customerId) {
					console.warn('用户未登录，无法获取购物车信息');
					return;
				}
				
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: `http://localhost:8080/api/carts/${this.customerId}`,
							method: 'GET',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});
					
					// 根据后端返回的数据结构进行处理
					if (res.data.code === 200 && Array.isArray(res.data.data)) {
						this.cartItems = res.data.data.map(item => ({
							...item,
							// 映射后端字段到前端使用的字段
							productId: item.productId,
							productName: item.name,
							price: item.price,
							buyNum: item.buyNum,
							cartId: item.cartId,
							selected: false
						}));
						this.setCartCount(this.cartItems.length);
					} else {
						console.error('获取购物车失败:', res.data.msg || '数据格式错误');
						uni.showToast({
							title: res.data.msg || '获取购物车失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取购物车失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			toggleSelectItem(item) {
				item.selected = !item.selected;
			},
			toggleSelectAll() {
				const newValue = !this.isAllSelected;
				this.cartItems.forEach(item => {
					item.selected = newValue;
				});
			},
			async increaseQuantity(item) {
				item.buyNum++;
				await this.updateCartItem(item);
			},
			async decreaseQuantity(item) {
				if (item.buyNum > 1) {
					item.buyNum--;
					await this.updateCartItem(item);
				}
			},
			async updateCartItem(item) {
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://localhost:8080/api/carts',
							method: 'PUT',
							data: {
								cartId: item.cartId,
								buyNum: item.buyNum
							},
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});
					
					if (res.data.code !== 200) {
						console.error('更新购物车失败:', res.data.msg || '未知错误');
						uni.showToast({
							title: res.data.msg || '更新失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('更新购物车失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			async removeFromCart(cartId) {
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: `http://localhost:8080/api/carts/${cartId}`,
							method: 'DELETE',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});
					
					if (res.data.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						this.fetchCartItems();
					} else {
						console.error('删除商品失败:', res.data.msg || '未知错误');
						uni.showToast({
							title: res.data.msg || '删除失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('删除商品失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			async placeOrder() {
				const selectedItems = this.cartItems.filter(item => item.selected);
				if (selectedItems.length === 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					});
					return;
				}

				// 检查是否选择了收货地址
			if (!this.selectedAddress || !this.selectedAddress.addressId) {
				uni.showToast({
					title: '请选择收货地址',
					icon: 'none'
				});
				return;
			}

			// 构建订单项数组
			const orderItems = selectedItems
			// .filter(i => i && i.productId && i.price != null && i.buyNum > 0) // 过滤空/脏数据
			.map(item => ({
				productId: item.productId,
				buyNum: item.buyNum,
				name: item.productName,
				price: item.price
			}));
			
			console.log('发送的订单项', JSON.stringify(orderItems));

				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://localhost:8080/api/orders',
							method: 'POST',
							data: {
								customerId: this.customerId,
								addressId: this.selectedAddress.addressId,
								items: orderItems
							},
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});

					if (res.data.code === 200) {
						uni.showToast({
							title: '下单成功',
							icon: 'success'
						});
						this.fetchCartItems(); // 刷新购物车
					} else {
						uni.showToast({
							title: res.data.msg || '下单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('下单失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			async loadAddresses() {
				if (!this.customerId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: `http://localhost:8080/api/addresses?customerId=${this.customerId}`,
							method: 'GET',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});
					
					if (res.data.code === 200 && Array.isArray(res.data.data)) {
						// 适配后端返回的数据结构
						this.addresses = res.data.data.map(addr => ({
							addressId: addr.addressId,
							customerId: addr.customerId,
							province: addr.address, // 后端address字段对应前端province字段
							city: "", // 后端没有city字段，留空
							region: addr.region,
							detailAddress: addr.detailAddress,
							isDefault: addr.defaultAddress === 1, // 后端defaultAddress字段对应前端isDefault字段
							name: addr.name, // 后端没有name字段，需要额外获取或留空
							phone: addr.phone // 后端没有phone字段，需要额外获取或留空
						}));
						this.showAddressPopup = true;
						
						// 如果还没有选择地址，自动选择默认地址或第一个地址
						if (!this.selectedAddress && this.addresses.length > 0) {
							const defaultAddress = this.addresses.find(addr => addr.isDefault);
							this.selectedAddress = defaultAddress || this.addresses[0];
						}
					} else {
						console.error('获取地址失败:', res.data.msg || '数据格式错误');
						uni.showToast({
							title: res.data.msg || '获取地址失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取地址失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			selectAddress(address) {
				this.selectedAddress = address;
				this.showAddressPopup = false;
			},
			addAddress() {
				// 跳转到地址添加页面
				uni.navigateTo({
					url: '/pages/address/add'
				});
			}
		},
		onLoad() {
			this.fetchCartItems();
			// 页面加载时尝试加载地址信息
			this.$nextTick(() => {
				this.loadAddresses();
			});
		}
	};
</script>

<style>
	.cart-container {
		padding: 20rpx;
	}

	.cart-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #e0e0e0;
	}

	.select-all {
		display: flex;
		align-items: center;
	}

	.select-all checkbox {
		margin-right: 10rpx;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #e0e0e0;
	}

	.item-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin: 0 20rpx;
	}

	.quantity-selector {
		display: flex;
		align-items: center;
		margin-top: 10rpx;
	}

	.quantity-selector input {
		width: 60rpx;
		text-align: center;
		margin: 0 10rpx;
	}

	.cart-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		margin-top: 20rpx;
	}

	.cart-footer button {
		background-color: #e91e63;
		color: white;
		border: none;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}
	
	/* 地址选择样式 */
	.address-selector {
		margin: 20rpx 0;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
	}
	
	.section-title {
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.address-info {
		padding: 15rpx;
		background-color: white;
		border-radius: 8rpx;
		border: 1rpx solid #e0e0e0;
	}
	
	.address-name {
		font-weight: bold;
		margin-right: 20rpx;
	}
	
	.address-phone {
		color: #666;
	}
	
	.address-detail {
		display: block;
		margin-top: 10rpx;
		color: #333;
		font-size: 28rpx;
	}
	
	.no-address {
		color: #999;
		font-style: italic;
	}
	
	/* 地址弹窗样式 */
	.address-popup {
		background-color: white;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 20rpx;
		max-height: 80vh;
		overflow-y: auto;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #e0e0e0;
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.close-btn {
		font-size: 40rpx;
		color: #999;
	}
	
	.address-list {
		margin: 20rpx 0;
	}
	
	.address-item {
		padding: 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		position: relative;
	}
	
	.address-item.selected {
		border-color: #e91e63;
		background-color: #fff0f4;
	}
	
	.address-main {
		margin-bottom: 10rpx;
	}
	
	.address-tag {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background-color: #e91e63;
		color: white;
		padding: 5rpx 10rpx;
		border-radius: 5rpx;
		font-size: 24rpx;
	}
	
	.add-address-btn {
		text-align: center;
		padding: 20rpx;
		color: #e91e63;
		font-weight: bold;
		border-top: 1rpx solid #e0e0e0;
		margin-top: 20rpx;
	}
</style>